<?php

namespace common\models\es;

use Yii;
use yii\elasticsearch\ActiveRecord;


class EsComProducts extends ActiveRecord
{

    public static $index = 'pdd_com_products';

    /**
     * 相当于定义了数据库
     */
    const INDEX = 'pdd_com_products';

    /**
     * 相当于定义了数据表
     */
    const TYPE = '_doc';


    /**
     * 需要返回的字段
     * @return array|string[]
     */
    public function attributes()
    {
        $mapConfig = self::mappingConfig();
        return array_keys($mapConfig['properties']);
    }

    /**
     * setting
     * @return array
     */
    private static function settings()
    {
        return [
            'number_of_shards' => 5, //创建5个分片
            'number_of_replicas' => 0, // 分片下有一个副本
        ];
    }


    /**
     * 删除索引
     */
    public function deleteIndex()
    {
        $deleteParams = ['index' => self::INDEX];
        Yii::$app->elasticsearch->indices()->delete($deleteParams);
    }

    /**
     * @param bool $delete
     * 初始化order 索引
     * @return
     */
    public function initIndex(bool $delete = true)
    {
        if ($delete) {
            $this->deleteIndex();
        }
        $params = [
            'index' => self::INDEX,
            'body' => [
                'settings' => static::settings(),
                'mappings' => [self::TYPE => static::mappingConfig()
                ]

            ],
            'include_type_name' => true //兼容老es
        ];
        return Yii::$app->elasticsearch->indices()->create($params);
    }


    /**
     * 批量同步数据
     * @param array $data
     * @return array
     */
    public function syncData(array $data)
    {
        $params = [];
        foreach ($data as $k => $item) {
            if (!isset($item['id'])) continue;
            $params['body'][] = [
                'index' => [
                    '_index' => self::INDEX,
                    '_type' => self::TYPE,
                    '_id' => $item['id'],
                ],
            ];
            $params['body'][] = $item;
        }
        return Yii::$app->elasticsearch->bulk($params);
    }


    /**
     * 批量更新部分字段数据
     * @param array $ids
     * @param array $data ['is_delete' => 1]
     * @return bool
     */
    public function updateAllData(array $ids,array $data)
    {
        $params = [];
        foreach ($ids as  $id) {
            $params['body'][] = [
                'update' => [
                    '_index' => self::INDEX,
                    '_type' => self::TYPE,
                    '_id' => $id,
                ],
            ];
            $params['body'][] = ['doc' => $data];
        }
        $res = Yii::$app->elasticsearch->bulk($params);
        if (isset($res['errors']) && $res['errors'] == false) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 按条件更新
     * @param array $where
     * @param array $data
     * @return
     */
    public function updateByWhere(array $where,array $data)
    {
        $fields = '';
        foreach ($data as $k=>$v){
            $fields .="ctx._source.{$k} = $v;";
        }
        $fields = trim($fields,';');

        $params = [
            'index' => self::INDEX,
            'type' => self::TYPE,
            'body' => [
                'query' => [
                    'bool'=>['must'=>[]]
                ],
                'script'=>[
                    "source"=> $fields,
                    'lang'=>'painless'

                ]
            ]
        ];

        foreach ($where as $key=>$val){
            $params['body']['query']['bool']['must'][] = [
                'term' => [
                    $key =>$val
                ]
            ];
        }

        $res = Yii::$app->elasticsearch->updateByQuery($params);

        return $res;
    }


    /**
     * mapping
     * @return array
     */
    private static function mappingConfig()
    {
        return [
            'properties' => [
                'id' => [
                    'type' => 'long'
                ],
                'title' => [
                    'type' => 'keyword'
                ],
                'cid' => [
                    'type' => 'integer'
                ],
                'uid' => [
                    'type' => 'integer'
                ],
                'num_iid' => [
                    'type' => 'keyword'
                ],
                'store_id' => [
                    'type' => 'long'
                ],
                'platform' => [
                    'type' => 'integer'
                ],
                'copy_status' => [
                    'type' => 'integer'
                ],
                'copy_times' => [
                    'type' => 'integer'
                ],
                'remark' => [
                    'type' => 'text',
                    'analyzer' => 'ik_smart',
                ],
                'prices' => [
                    'type' => 'integer'
                ],
                'mall_id' => [
                    'type' => 'long'
                ],
                'out_mall_id' => [
                    'type' => 'long'
                ],
                'mall_name' => [
                    'type' => 'keyword',
                ],
                'is_delete' => [
                    'type' => 'integer',
                ],
                'created_at' => [
                    'type' => 'date',
                    'format' => 'strict_date_optional_time||epoch_second||epoch_millis'
                ],
                'updated_at' => [
                    'type' => 'integer'
                ]
            ]
        ];
    }
}
